package com.yc.testupload;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.sql.Connection;
import java.sql.SQLException;
import com.yc.testupload.util.DatabaseUtil;

/**
 * 数据库连接测试工具类
 * 用于诊断数据库连接问题并提供详细的连接状态信息
 */
public class DatabaseConnectionTester {
    
    private static final Logger logger = LogManager.getLogger(DatabaseConnectionTester.class);
    
    /**
     * 测试数据库连接并返回详细状态信息
     * @return 包含连接状态和消息的Map
     */
    public static java.util.Map<String, Object> testConnectionDetailed() {
        java.util.Map<String, Object> result = new java.util.HashMap<>();
        Connection conn = null;
        
        try {
            long startTime = System.currentTimeMillis();
            logger.info("开始测试数据库连接...");
            logger.info("连接URL: {}", DatabaseUtil.getProperties().getProperty("jdbc.url"));
            logger.info("用户名: {}", DatabaseUtil.getProperties().getProperty("jdbc.username"));
            
            conn = DatabaseUtil.getConnection();
            long endTime = System.currentTimeMillis();
            
            boolean isConnected = conn != null && !conn.isClosed();
            
            result.put("success", isConnected);
            result.put("message", isConnected ? "数据库连接成功" : "数据库连接失败");
            result.put("connectionTimeMs", endTime - startTime);
            
            if (isConnected) {
                logger.info("数据库连接测试成功！连接耗时: {}ms", endTime - startTime);
            } else {
                logger.error("数据库连接测试失败！");
            }
            
        } catch (SQLException e) {
            logger.error("数据库连接异常: {}", e.getMessage());
            logger.debug("异常详情:", e);
            
            result.put("success", false);
            result.put("message", "数据库连接异常: " + e.getMessage());
            result.put("errorType", e.getClass().getSimpleName());
            
            // 分析常见的连接问题
            String errorMsg = e.getMessage().toLowerCase();
            if (errorMsg.contains("timed out")) {
                result.put("suggestion", "连接超时，请检查网络连接和数据库服务器是否可达");
            } else if (errorMsg.contains("access denied")) {
                result.put("suggestion", "访问被拒绝，请检查用户名和密码是否正确");
            } else if (errorMsg.contains("unknown database")) {
                result.put("suggestion", "数据库不存在，请检查数据库名称是否正确");
            } else {
                result.put("suggestion", "请检查数据库服务器状态和网络连接");
            }
        } finally {
            if (conn != null) {
                DatabaseUtil.closeConnection(conn);
            }
        }
        
        return result;
    }
    
    /**
     * 获取数据库连接配置信息
     * @return 配置信息Map
     */
    public static java.util.Map<String, String> getConnectionConfig() {
        java.util.Map<String, String> config = new java.util.HashMap<>();
        config.put("url", DatabaseUtil.getProperties().getProperty("jdbc.url"));
        config.put("username", DatabaseUtil.getProperties().getProperty("jdbc.username"));
        config.put("driver", DatabaseUtil.getProperties().getProperty("jdbc.driver"));
        config.put("initialSize", DatabaseUtil.getProperties().getProperty("jdbc.initialSize"));
        config.put("maxActive", DatabaseUtil.getProperties().getProperty("jdbc.maxActive"));
        config.put("maxIdle", DatabaseUtil.getProperties().getProperty("jdbc.maxIdle"));
        config.put("minIdle", DatabaseUtil.getProperties().getProperty("jdbc.minIdle"));
        return config;
    }
}